//
//  InsurancePolicyListViewController.m
//  CPICApp
//
//  Created by lizhiwei on 13-3-14.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "InsurancePolicyListViewController.h"
#import "RCAlertViewUtil.h"
#import "InsurancePolicyDetailViewController.h"
#import "AppDelegate.h"
#import "HistroyInsurancePolicyViewController.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"
#import "WSqlite.h"

@interface InsurancePolicyListViewController ()

@end

@implementation InsurancePolicyListViewController
@synthesize TableInsurancePolicyList;
@synthesize TableInsurancePolicyHistory;
@synthesize progress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"保单列表";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"保单列表");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"保单列表");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"保单列表");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    
    TableInsurancePolicyList = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-100) style:UITableViewStyleGrouped];
    TableInsurancePolicyList.dataSource = self;
    TableInsurancePolicyList.delegate = self;
    TableInsurancePolicyList.opaque = NO;
    TableInsurancePolicyList.backgroundView = nil;
    TableInsurancePolicyList.autoresizingMask = UIViewContentModeTop;
    TableInsurancePolicyList.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    //TableInsurancePolicyList.backgroundColor=[UIColor clearColor];
    [self.view addSubview:TableInsurancePolicyList];
    
    TableInsurancePolicyHistory = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-244, self.view.frame.size.width, 300) style:UITableViewStyleGrouped];
    TableInsurancePolicyHistory.dataSource = self;
    TableInsurancePolicyHistory.delegate = self;
    TableInsurancePolicyHistory.opaque = NO;
    TableInsurancePolicyHistory.backgroundView = nil;
    TableInsurancePolicyHistory.autoresizingMask = UIViewContentModeTop;
    TableInsurancePolicyHistory.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    //TableInsurancePolicyHistory.backgroundColor=[UIColor clearColor];
    [self.view addSubview:TableInsurancePolicyHistory];
    
    //初始化数组
    arrInsuranceTypeOne=[[NSMutableArray alloc]initWithObjects:@"交强险",@"商业险",@"交强险",nil];
    arrInsuranceTypeTwo=[[NSMutableArray alloc]initWithObjects:@"商业险",@"商业险",@"商业险",nil];
    arrInsuranceStartDate=[[NSMutableArray alloc]initWithObjects:@"2013-03-14",@"2013-03-15",@"2013-03-16", nil];
    arrInsuranceEndDate=[[NSMutableArray alloc]initWithObjects:@"2014-03-14",@"2014-03-15",@"2014-03-16", nil];
    
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bInsurancePolicySearch=FALSE;
    [self getCarInfo];
    
    [self setEvaluationRequest];
}
-(void)getCarInfo
{
    RCCarListInfo *rcCarListInfo=[[RCCarListInfo alloc]initCarListInfoView];
    rcCarListInfo.carInfoDelegate=self;
    [rcCarListInfo setCarListRequest:YES];
    [rcCarListInfo setHidden:YES];
    [self.view addSubview:rcCarListInfo];
    [rcCarListInfo release];
}
-(void)getCarListInfo:(BOOL)bCarInfo
{
    
}
-(void)getCarDetailInfo
{
    [self setInsPolicyListRequest];
}
-(void) ClickCallOutBtn
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (myDelegate.bInsurancePolicySearch==FALSE) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        if ([Flag isEqualToString:@"0"])
        {
            [self IFServiceEvaluation];
            Flag = @"1";
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(void)setEvaluationRequest
{
    NSLog(@"==================");
    NSString *serviceid =@"40101";
    NSString *servicename =@"保单查询";
    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
    [ifserviceevaluation setIfServiceEvaluationRequest];
    [ifserviceevaluation setHidden:YES];
    [self.view addSubview:ifserviceevaluation];
    [ifserviceevaluation release];
}
-(void) IFServiceEvaluation
{
    NSString *serviceid =@"40101";
    NSString *servicename =@"保单查询";
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if ([myDefaults stringForKey:serviceid]) {
        NSString *strEvaluate=[myDefaults stringForKey:serviceid];
        if ([strEvaluate isEqualToString:@"1"]) {
            AddServiceEvaluationViewController *serviceevluation = [[AddServiceEvaluationViewController alloc]initView:serviceid withserviceName:servicename];
            [[AppDelegate app].unc pushViewController:serviceevluation animated:YES];
            [serviceevluation release];
        }
        else
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView==TableInsurancePolicyList)
    {
        return [arrInsPolicyList count];
    }
    else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == TableInsurancePolicyList)
    {
        return 50;
    }
    else
    {
        return 40;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView==TableInsurancePolicyList)
    {
        static NSString * kCellID = @"cellID";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            //设置选中某行的风格颜色
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            //cell.selectionStyle = UITableViewCellEditingStyleNone;
            cell.backgroundColor = [UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f];
            
            UIView *view = [[UIView alloc] initWithFrame:cell.frame];
            
            dicInsPolicyList = [arrInsPolicyList objectAtIndex:indexPath.row];
            
            NSString *productname = [[NSString alloc] initWithFormat:@"%@",[dicInsPolicyList objectForKey:@"productname"]];
            
            NSString *StartDate = [[NSString alloc] initWithFormat:@"%@",[dicInsPolicyList objectForKey:@"startdate"]];
            
            NSString *EndDate = [[NSString alloc] initWithFormat:@"%@",[dicInsPolicyList objectForKey:@"enddate"]];
            
            //字符串截断
            StartDate =[StartDate substringWithRange:NSMakeRange(0,10)];
            EndDate =[EndDate substringWithRange:NSMakeRange(0,10)];
            
            UILabel *labelType= [[UILabel alloc] init];
            [labelType setText:productname];
            [labelType setFrame:CGRectMake(20, 4.5, 250, 30)];
            [labelType setFont:[UIFont systemFontOfSize:14.0]];
            [labelType setBackgroundColor:[UIColor clearColor]];
            
            UILabel *labelTitle= [[UILabel alloc] init];
            [labelTitle setText:StartDate];
            [labelTitle setFrame:CGRectMake(20, 20.5, 120, 30)];
            [labelTitle setFont:[UIFont systemFontOfSize:14.0]];
            [labelTitle setBackgroundColor:[UIColor clearColor]];
            
            UILabel *labelContent = [[UILabel alloc] init];
            NSString * EndDateTime = [NSString stringWithFormat:@"至 %@",EndDate];
            [labelContent setText:EndDateTime];
            [labelContent setFrame:CGRectMake(105,20.5, 140, 30)];
            [labelContent setFont:[UIFont systemFontOfSize:14.0]];
            [labelContent setBackgroundColor:[UIColor clearColor]];
            
            
            /*UILabel *labelTypeTwo= [[UILabel alloc] init];
             [labelTypeTwo setText:[arrInsuranceTypeTwo objectAtIndex:indexPath.row]];
             [labelTypeTwo setFrame:CGRectMake(20, 40, 50, 20)];
             [labelTypeTwo setFont:[UIFont systemFontOfSize:14.0]];
             [labelTypeTwo setBackgroundColor:[UIColor clearColor]];
             
             UILabel *labelPrice = [[UILabel alloc] init];
             [labelPrice setText:[arrInsuranceEndDate objectAtIndex:indexPath.row]];
             [labelPrice setFrame:CGRectMake(70, 40, 100, 20)];
             [labelPrice setFont:[UIFont systemFontOfSize:14.0]];
             [labelPrice setBackgroundColor:[UIColor clearColor]];
             
             UILabel *labelSeckillPrice = [[UILabel alloc] init];
             NSString * EndDateTimeStr = [NSString stringWithFormat:@"至 %@",[arrInsuranceEndDate objectAtIndex:indexPath.row]];
             [labelSeckillPrice setText:EndDateTimeStr];
             [labelSeckillPrice setFrame:CGRectMake(145, 40, 100, 20)];
             [labelSeckillPrice setFont:[UIFont systemFontOfSize:14.0]];
             [labelSeckillPrice setBackgroundColor:[UIColor clearColor]];*/
            
            [view addSubview:labelType];
            //[view addSubview:labelTypeTwo];
            [view addSubview:labelTitle];
            [view addSubview:labelContent];
            //[view addSubview:labelPrice];
            //[view addSubview:labelSeckillPrice];
            
            //[labelTypeTwo release];
            [labelType release];
            [labelTitle release];
            [labelContent release];
            //[labelPrice release];
            //[labelSeckillPrice release];
            
            [cell addSubview:view];
            [view release];
        }
     return cell;   
    }
    else
    {
        static NSString *Identifier=@"Identifier";
        UITableViewCell *cell=(UITableViewCell *)[TableInsurancePolicyHistory dequeueReusableCellWithIdentifier:Identifier];
        if (cell==nil)
        {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
            cell.selectionStyle=UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            //设置选中某行的风格颜色
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UIView *view = [[UIView alloc] initWithFrame:cell.frame];
            
            UILabel *labelTitle= [[UILabel alloc] init];
            [labelTitle setText:@"历史保单"];
            [labelTitle setFrame:CGRectMake(70, 5, 100, 30)];
            [labelTitle setFont:[UIFont systemFontOfSize:14.0]];
            [labelTitle setBackgroundColor:[UIColor clearColor]];
            [view addSubview:labelTitle];
            [labelTitle release];
            [cell addSubview:view];
            [view release];
        }
    return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView==TableInsurancePolicyList)
    {
        NSMutableDictionary *dictItem=[arrInsPolicyList objectAtIndex:indexPath.row];
        NSString *strPolicy=[[NSString alloc]initWithFormat:@"%@",[dictItem valueForKey:@"policyno"]];
        InsurancePolicyDetailViewController *insdetail = [[InsurancePolicyDetailViewController alloc]init];
        insdetail.strPolicyNo=strPolicy;
        NSLog(@"strPolicyNo:%@",strPolicy);
        [[AppDelegate app].unc pushViewController:insdetail animated:YES];
        [insdetail release];
        [strPolicy release];
    }
    else
    {
        HistroyInsurancePolicyViewController *histroyins = [[HistroyInsurancePolicyViewController alloc]init];
        [[AppDelegate app].unc pushViewController:histroyins animated:YES];
        [histroyins release];
    }
}

-(void)setInsPolicyListRequest//向太保移动平台发送请求报文
{
    Flag = @"0";
    
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
    NSUserDefaults *myDefaultsCarInfo=[NSUserDefaults standardUserDefaults];
    NSDictionary *dictCarInfo=[myDefaultsCarInfo dictionaryForKey:DICT_CAR_CUSTOMERINFO];
    if (dictCarInfo!=nil)
    {
        if ([dictCarInfo valueForKey:@"license"])
        {
            NSString *strLincense=[dictCarInfo valueForKey:@"license"];
            if ([strLincense isEqualToString:@""]) {
                [self justShowMessage:@"车牌号码为空,请到车辆设置页面去补充" title:@"注意"];
                return;
            }
        }else{
            [self justShowMessage:@"车牌号码为空,请到车辆设置页面去补充" title:@"注意"];
            return;
        }
        if ([dictCarInfo valueForKey:@"iDNum"]) {
            NSString *strIDNum=[dictCarInfo valueForKey:@"iDNum"];
            if ([strIDNum isEqualToString:@""]) {
                [self justShowMessage:@"证件号码号码为空,请到车辆设置页面去补充" title:@"注意"];
                return;
            }
        }else
        {
             [self justShowMessage:@"证件号码为空,请到车辆设置页面去补充" title:@"注意"];
             return;
        }
        if ([dictCarInfo valueForKey:@"policyHolder"]) {
            NSString *strPolicyHolder=[dictCarInfo valueForKey:@"policyHolder"];
            if ([strPolicyHolder isEqualToString:@""]) {
                [self justShowMessage:@"投保人为空,请到车辆设置页面去补充" title:@"注意"];
                return;
            }
        }else
        {
             [self justShowMessage:@"投保人为空,请到车辆设置页面去补充" title:@"注意"];
             return;
        }
    }
    else
    {
        [self justShowMessage:@"资料不完整,请到车辆设置页面去补充" title:@"注意"];
        return;
    }
    WSqlite *sql =[WSqlite Instance];
    NSLog(@"查的车辆是:%@",[dictCarInfo valueForKey:@"license"]);
    arrInsPolicyList=[sql getPolictData:[dictUserInfo valueForKey:@"UserAccount"] withTag:@"1" withPlateNo:[dictCarInfo valueForKey:@"license"]];
    if ([arrInsPolicyList count]>0) {
        [TableInsurancePolicyList reloadData];
    }
    else
    {
        NSString * useraccount = [dictUserInfo valueForKey:@"UserAccount"];
        NSString *strRequestData=[NSString stringWithFormat:@"{\"userAccount\":\"%@\",\"UserName\":\"%@\",\"certificateno\":\"%@\",\"PlateNo\":\"%@\"}",useraccount,[dictCarInfo valueForKey:@"policyHolder"],[dictCarInfo valueForKey:@"iDNum"],[dictCarInfo valueForKey:@"license"]];
        ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
        //设置需要POST的数据，这里提交两个数据，A=a&B=b
        [request setPostValue:@"40101" forKey:@"RequestCode"];
        [request setPostValue:strRequestData forKey:@"RequestData"];
        
        [request setDelegate:self];
        [request setDidFailSelector:@selector(ResponseFail:)];
        [request setDidFinishSelector:@selector(ResonseSuccess:)];
        [request startAsynchronous];
        
        showProgress = YES;
        if (showProgress)
        {
            progress= [[MBProgressHUD alloc]initWithView:self.view];
            [self.view addSubview:progress];
            [self.view bringSubviewToFront:progress];
            progress.labelText = @"加载中...";
            [progress show:YES];
            showProgress = NO;
        }
    }

}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictopinion=[dictResponse objectForKey:@"validPolicyList"];
    arrInsPolicyList=[dictopinion objectForKey:@"data"];
    if ([arrInsPolicyList count]==0) {
        [self justShowMessage:@"保单列表数据为空!" title:@"提示"];
    }
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    
    NSUserDefaults *myDefaultsCarInfo=[NSUserDefaults standardUserDefaults];
    NSDictionary *dictCarInfo=[myDefaultsCarInfo dictionaryForKey:DICT_CAR_CUSTOMERINFO];
    if ([arrInsPolicyList count]>0) {
        
    WSqlite *sql =[WSqlite Instance];
    NSLog(@"插入的车辆为:%@",[dictCarInfo valueForKey:@"license"]);
    [sql insertPolicyData:arrInsPolicyList withUserAccount:[dictUserInfo valueForKey:@"UserAccount"] withTag:@"1" withPlateNo:[dictCarInfo valueForKey:@"license"] withCertificateno:[dictCarInfo valueForKey:@"iDNum"]];
    }

    
    [TableInsurancePolicyList reloadData];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    [TableInsurancePolicyList release];
    [TableInsurancePolicyHistory release];
    [progress release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
